import { createAction, createReducer, ActionType, createAsyncAction } from 'typesafe-actions';
import { Dispatch } from 'redux';
import Axios from 'axios';

export interface WordUserDto {
    username: string
}
export type WordUserState = WordUserDto;

/**
* 更新WordSource的内容
* @param wordValue WordListState子类型 
*/
const refresh = createAction('WORD_USER/REFRESH')<WordUserState>();

const fetchActions = createAsyncAction(
    'WORD_USER/FETCH/REQUEST',
    ['WORD_USER/FETCH/SUCCESS', (res: WordUserDto) => res],
    ['WORD_USER/FETCH/FAILURE', (err: Error) => err],
    'WORD_USER/FETCH/CANCEL',
)();

export type Actions = ActionType<typeof refresh> | ActionType<typeof fetchActions>;

export const fetch = () =>
    async (dispatch: Dispatch) =>
        Axios.get<WordUserDto>(`auth/info`, { baseURL: "/api/" })
            .then(res => dispatch(fetchActions.success(res.data)))
            .catch(error => dispatch(fetchActions.failure(error)))


const initialState: WordUserState = {
    username: "初始化"
};

export const Reducer = createReducer<WordUserState, Actions>(initialState)
    .handleAction(refresh, (_, action) => action.payload)
    .handleAction(fetchActions.success, (_, action) => action.payload)